# -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations

#########################################################################
## This is a samples controller
## - index is the default action of any application
## - user is required for authentication and authorization
## - download is for downloading files uploaded in the db (does streaming)
## - call exposes all registered services (none by default)
#########################################################################
#print response
def index():
    buttons=[
          ('Live Demo',URL('default','proxy')+'/${link}','_self','Live demo for ${feature}','positive left button','book'),
          ('Docs',URL('plugin_PowerGrid','data',args=['read','features'])+'/${id}','_blank','Docs for ${feature}','modal right button','rightarrow'),
       ]
    
    if auth.has_membership('admin'):
        buttons+= [('edit',URL('plugin_PowerGrid','data',args=['update','features'])+'/${id}','_blank','Editing Record ${id}','refreshmodal middle button', 'pen'),
          ('delete',URL('plugin_PowerGrid','data',args=['delete','features'])+'/${id}','_blank','Are you sure you want to delete record ${id}','confirmationmodal right negative button', 'cross')]
    
    from plugin_PowerGrid.PowerGrid import PowerGrid
    p = PowerGrid(
           callback=URL('default','features', extension='json'),
           buttons=buttons,
           addurl=URL('plugin_PowerGrid','data',args=['create','features']), 
           hideaddbutton=False if auth.has_membership('admin') else True,
           headers=[['feature','Feature'], ['text','What?']],
           minH=600,minW=800,
           options=dict(colsWidth=[200,400],find='text',rows=10)

    )
    return dict(p=p)

def proxy():
    redirect(URL('default',request.args(0)))

def features():
    from plugin_PowerGrid.CallBack import CallBack        
    return CallBack(db.features.id>0)

def blog():
    response.view = 'default/index.html'
    # passing a custom jquery template bu string
    # ${fieldname} evaluates to field value
    # {{html htmlValueField}} parses the html
    # Buttons:
    #   - class 'modal' to open in modal (when used, target needs to be '_blank')
    #   - class 'button' to decorate button - see CSS3 Buttons documentation
    #   - <span class='icon plus'></span> inside <a class='button'> to decorate button with icon (see CSS3 buttons docs)
    #   - recommend to always wrap with div, ul, p
    template = """   
               <div class='powergrid-post' style='height:500px !important;border:none !important;'>
                 <hr />
                 <h1 style='background-color:#ccc;line-height:60px;height:60px;width:100%;'>&nbsp;&nbsp;${name} - Posted on: ${date}</h1>
                 <hr />
                 <div><a class='modal' target='_blank' href='/PowerGrid/default/download/${picture}'><img height='250' src='/PowerGrid/default/download/${picture}' /></a></div>
                 <div class='powergrid_buttons'>
                    <a title='Comments for post ${id}'   href="/PowerGrid/plugin_PowerGrid/data/select/comments/${id}" class='button modal' target='_blank'>Comments</a>
                    <a title='Edit post ${id}' minH='800' href="/PowerGrid/plugin_PowerGrid/data/update/products/${id}" class='button positive refreshmodal' target='_blank'>Edit Post</a>
                 </div>
                 <br />
                 <br />
                <div>${manufacturer} / ${group_id} </div>
                <div style='clear:both;'></div>
                <div><p>{{html text}}</p></div>
              </div>
              """
    
    
    from plugin_PowerGrid.PowerGrid import PowerGrid
    p = PowerGrid(
           callback=URL('default','callback_with_virtualfields', extension='json'),
           addurl=URL('plugin_PowerGrid','data',args=['create','products']), 
           hideaddbutton=False,
           addLabel="New post",
           headers=[['','']], #comment or define headers here to include sorters
           template=template,
           _style='border:none;',
           options=dict(colsWidth=[None],
                        rows=2,
                        width=760,
                        clickFx=False,
                        hoverFx=False,
                        findsName=[['text','Search on post']],
                        find='text',
                        resultText= 'Showing {from} - {to} to {total} posts',
                        sortOrder='desc',
                        sortName='id')

    )
    p.insert(0,CENTER(H1('My Powerful blog post pagination')))
    p.insert(1,CENTER(H2('Customizable html template and css!')))
    p.insert(2,BR())
    p.insert(3,STYLE("""#wrapper {width: 800px !important;}"""))
    return dict(p=p) 

def jscallbacks():
    response.view = 'default/index.html'
    from plugin_PowerGrid.PowerGrid import PowerGrid
    p = PowerGrid(
                  callback=URL('default','callback', extension='json') if request.args(0) != 'error' else '',
                  buttons=[
                            ('details',URL('plugin_PowerGrid','data',args=['read','products'])+'/${id}','_blank','Details of Record ${id}','modal positive button','magnifier'),
                    
                         ],
                  addurl=URL('plugin_PowerGrid','data',args=['create','products']), 
                  addLabel='Add New Record',   
                  addTitle='You are adding a new record',              
                  headers=[['id','Id'], ['name','Name'], ['manufacturer','Manufacturer'],['group_id','Group ID']],
                  hidecontrolbuttons=True,
                  #hiderefreshbutton=True,
                  #hideaddbutton=True,
                  #_id="banana",
                  #target="melancia",
                  #searchBy='equal',
                  #templatetype='grid',
                  #minW=1600,
                  minH=500,
                  options=dict(colsWidth=[30,200,200,100],
                               #width=700,
                               #buttonBackTitle='Back',
                               #buttonMax=4,
                               #buttonNextTitle='Next',
                               success="""js[function(){alert('Executed on load success');}]js""" if request.args(0) == 'success' else ''  ,
                               before="""js[function(){alert('Executed before load');}]js""" if request.args(0) == 'before' else '',
                               error="""js[function(){alert('Executed when load error');}]js""" if request.args(0) == 'error' else '',
                               #buttonOption=False,
                               #buttonsWidth=200
                               #buttonTitle='oi',
                               #clickFx=False,
                               #debug=True,
                               #find='name',search='J',
                               #searchOption=False,
                               #searchButtonLabel='Buscar',
                               #searchButtonTitle='Clique para buscar',
                               #searchFocus=False,
                               #cache=True,
                               #contentType='application/x-www-form-urlencoded; charset=utf-8',
                               #type='get',
                               #dataType='jsonp',
                               #jsonp=True,
                               #jsonpCallback='callback',
                               #findsName=[['name','name']],
                               #hoverFx=False,
                               #loadingOption=True,
                               #loadingText='Carregando...',
                               #messageOption=False,
                               #noResultOption=False,
                               #noResultText='I found nothing ',
                               #page=1,
                               #rows=3,
                               #rowsNumber=[3,25],
                               #params='&blablabla=45',
                               #resize=False,
                               #resultOption=False,
                               #resultText= 'Exibindo {from} - {to} de {total} registros',
                               #scroll=True,height=100,
                               #searchText='Busque aqui',
                               #sortName='name',
                               #sortOrder='asc',
                               #template='template',
                               #templateStyle='blabla',



                                   ),
                  )
    icon = SPAN(_class='clock icon')
    p.insert(0,DIV(A(icon,'On Error',_class='button',_href=URL('default','jscallbacks',args='error')),
                  
                  SPAN(XML('&nbsp;'*4)),
                  A(icon,'Before Load',_class='button',_href=URL('default','jscallbacks',args='before')),

                  SPAN(XML('&nbsp;'*4)),
                  A(icon,'After Successful Load',_class='button',_href=URL('default','jscallbacks',args='success')),

                  _style='margin-bottom:20px;margin-right:20px !important;'))

    return dict(p=p)

def buttons():
    response.view = 'default/index.html'
    from plugin_PowerGrid.PowerGrid import PowerGrid
    p = PowerGrid(
                  callback=URL('default','callback', extension='json'),
                  buttons=[
                            ('details',URL('plugin_PowerGrid','data',args=['read','products'])+'/${id}','_blank','Details of Record ${id}','modal positive left button','magnifier',[600,500]),
                            ('edit',URL('plugin_PowerGrid','data',args=['update','products'])+'/${id}','_blank','Editing Record ${id}','refreshmodal middle button', 'pen',[600,800]),
                            ('delete',URL('plugin_PowerGrid','data',args=['delete','products'])+'/${id}','_blank','Are you sure you want to delete record ${id}','confirmationmodal right negative button', 'cross'),
                            ('google','http://www.google.com/#hl=en-US&source=hp&q=${name}','_blank','Googling for ${name}','modal right button', 'pin',[900,600]),
                         ],
                  addurl=URL('plugin_PowerGrid','data',args=['create','products']), 
                  addLabel='Add New Record',   
                  addTitle='You are adding a new record',              
                  headers=[['id','Id'], ['name','Name'], ['manufacturer','Manufacturer'],['group_id','Group ID']],
                  #hidecontrolbuttons=True,
                  #hiderefreshbutton=True,
                  #hideaddbutton=True,
                  #_id="banana",
                  #target="melancia",
                  #searchBy='equal',
                  minH=800,
                  options=dict(colsWidth=[30,200,200,100],
                               #width=700,
                               #buttonBackTitle='Back',
                               #buttonMax=4,
                               #buttonNextTitle='Next',
                               #success="""js[function(){alert('Executed on success');}]js""",
                               #before="""js[function(){alert('Executed before');}]js""",
                               #error="""js[function(){alert('Executed on load error');}]js""",
                               #buttonOption=False,
                               #buttonsWidth=200
                               #buttonTitle='oi',
                               #clickFx=False,
                               #debug=True,
                               #find='name',search='J',
                               #searchOption=False,
                               #searchButtonLabel='Buscar',
                               #searchButtonTitle='Clique para buscar',
                               #searchFocus=False,
                               #cache=True,
                               #contentType='application/x-www-form-urlencoded; charset=utf-8',
                               #type='get',
                               #dataType='jsonp',
                               #jsonp=True,
                               #jsonpCallback='callback',
                               #findsName=[['name','name']],
                               #hoverFx=False,
                               #loadingOption=True,
                               #loadingText='Carregando...',
                               #messageOption=False,
                               #noResultOption=False,
                               #noResultText='I found nothing ',
                               #page=1,
                               #rows=3,
                               #rowsNumber=[3,25],
                               #params='&blablabla=45',
                               #resize=False,
                               #resultOption=False,
                               #resultText= 'Exibindo {from} - {to} de {total} registros',
                               #scroll=True,height=100,
                               #searchText='Busque aqui',
                               #sortName='name',
                               #sortOrder='asc',
                               #template='template',
                               #templateStyle='blabla',



                                   ),
                  )

    return dict(p=p)

def scroll():
    response.view = 'default/index.html'
    from plugin_PowerGrid.PowerGrid import PowerGrid
    p = PowerGrid(
                  callback=URL('default','callback', extension='json'),
                  buttons=[
                            ('details',URL('plugin_PowerGrid','data',args=['read','products'])+'/${id}','_blank','Details of Record ${id}','modal positive button','magnifier',[600,500]),

                         ],
                  addurl=URL('plugin_PowerGrid','data',args=['create','products']), 
                  addLabel='Add New Record',   
                  addTitle='You are adding a new record',              
                  headers=[['id','Id'], ['name','Name'], ['manufacturer','Manufacturer'],['group_id','Group ID']],
                  #hidecontrolbuttons=True,
                  #hiderefreshbutton=True,
                  #hideaddbutton=True,
                  #_id="banana",
                  #target="melancia",
                  #searchBy='equal',
                  options=dict(colsWidth=[30,200,200,100],
                               width=900,
                               #buttonBackTitle='Back',
                               #buttonMax=4,
                               #buttonNextTitle='Next',
                               #success="""js[function(){alert('Executed on success');}]js""",
                               #before="""js[function(){alert('Executed before');}]js""",
                               #error="""js[function(){alert('Executed on load error');}]js""",
                               buttonOption=False,
                               #buttonsWidth=200
                               #buttonTitle='oi',
                               #clickFx=False,
                               #debug=True,
                               #find='name',search='J',
                               #searchOption=False,
                               #searchButtonLabel='Buscar',
                               #searchButtonTitle='Clique para buscar',
                               #searchFocus=False,
                               #cache=True,
                               #contentType='application/x-www-form-urlencoded; charset=utf-8',
                               #type='get',
                               #dataType='jsonp',
                               #jsonp=True,
                               #jsonpCallback='callback',
                               #findsName=[['name','name']],
                               #hoverFx=False,
                               #loadingOption=True,
                               #loadingText='Carregando...',
                               #messageOption=False,
                               #noResultOption=False,
                               #noResultText='I found nothing ',
                               #page=1,
                               rows=100,
                               rowsNumber=[100],
                               #params='&blablabla=45',
                               #resize=False,
                               #resultOption=False,
                               #resultText= 'Exibindo {from} - {to} de {total} registros',
                               scroll=True,height=300,
                               #searchText='Busque aqui',
                               #sortName='name',
                               #sortOrder='asc',
                               #template='template',
                               #templateStyle='blabla',



                                   ),
                  )

    return dict(p=p)

def nocontrol():
    response.view = 'default/index.html'
    from plugin_PowerGrid.PowerGrid import PowerGrid
    p = PowerGrid(
                  callback=URL('default','callback', extension='json'),
                  buttons=[
                            ('details',URL('plugin_PowerGrid','data',args=['read','products'])+'/${id}','_blank','Details of Record ${id}','modal positive left button','magnifier',[600,500]),
                            ('edit',URL('plugin_PowerGrid','data',args=['update','products'])+'/${id}','_blank','Editing Record ${id}','refreshmodal middle button', 'pen',[600,800]),
                            ('delete',URL('plugin_PowerGrid','data',args=['delete','products'])+'/${id}','_blank','Are you sure you want to delete record ${id}','confirmationmodal right negative button', 'cross'),
                         ],
                  addurl=URL('plugin_PowerGrid','data',args=['create','products']), 
                  addLabel='Add New Record',   
                  addTitle='You are adding a new record',              
                  headers=[['id','Id'], ['name','Name'], ['manufacturer','Manufacturer'],['group_id','Group ID']],
                  hidecontrolbuttons=True,
                  #hiderefreshbutton=True,
                  #hideaddbutton=True,
                  #_id="banana",
                  #target="melancia",
                  #searchBy='equal',
                  options=dict(colsWidth=[30,200,200,100],
                               #width=700,
                               #buttonBackTitle='Back',
                               #buttonMax=4,
                               #buttonNextTitle='Next',
                               #success="""js[function(){alert('Executed on success');}]js""",
                               #before="""js[function(){alert('Executed before');}]js""",
                               #error="""js[function(){alert('Executed on load error');}]js""",
                               #buttonOption=False,
                               #buttonsWidth=200
                               #buttonTitle='oi',
                               #clickFx=False,
                               #debug=True,
                               #find='name',search='J',
                               #searchOption=False,
                               #searchButtonLabel='Buscar',
                               #searchButtonTitle='Clique para buscar',
                               #searchFocus=False,
                               #cache=True,
                               #contentType='application/x-www-form-urlencoded; charset=utf-8',
                               #type='get',
                               #dataType='jsonp',
                               #jsonp=True,
                               #jsonpCallback='callback',
                               #findsName=[['name','name']],
                               #hoverFx=False,
                               #loadingOption=True,
                               #loadingText='Carregando...',
                               #messageOption=False,
                               #noResultOption=False,
                               #noResultText='I found nothing ',
                               #page=1,
                               #rows=3,
                               #rowsNumber=[3,25],
                               #params='&blablabla=45',
                               #resize=False,
                               #resultOption=False,
                               #resultText= 'Exibindo {from} - {to} de {total} registros',
                               #scroll=True,height=100,
                               #searchText='Busque aqui',
                               #sortName='name',
                               #sortOrder='asc',
                               #template='template',
                               #templateStyle='blabla',



                                   ),
                  )

    return dict(p=p)

def defaultsearch():
    response.view = 'default/index.html'
    from plugin_PowerGrid.PowerGrid import PowerGrid
    p = PowerGrid(
                  callback=URL('default','callback', extension='json'),
                  buttons=[
                            ('details',URL('plugin_PowerGrid','data',args=['read','products'])+'/${id}','_blank','Details of Record ${id}','modal positive left button','magnifier',[600,500]),
                            ('edit',URL('plugin_PowerGrid','data',args=['update','products'])+'/${id}','_blank','Editing Record ${id}','refreshmodal middle button', 'pen',[600,800]),
                            ('delete',URL('plugin_PowerGrid','data',args=['delete','products'])+'/${id}','_blank','Are you sure you want to delete record ${id}','confirmationmodal right negative button', 'cross'),
                         ],
                  addurl=URL('plugin_PowerGrid','data',args=['create','products']), 
                  addLabel='Click here to add a new record',   
                  addTitle='You are adding a new record',              
                  headers=[['id','Id'], ['name','Name'], ['manufacturer','Manufacturer'],['group_id','Group ID']],
                  #hidecontrolbuttons=True,
                  #hiderefreshbutton=True,
                  #hideaddbutton=True,
                  #_id="banana",
                  #target="melancia",
                  #searchBy='equal',
                  options=dict(colsWidth=[30,200,200,100],
                               #width=700,
                               #buttonBackTitle='Back',
                               #buttonMax=4,
                               #buttonNextTitle='Next',
                               #success="""js[function(){alert('Executed on success');}]js""",
                               #before="""js[function(){alert('Executed before');}]js""",
                               #error="""js[function(){alert('Executed on load error');}]js""",
                               #buttonOption=False,
                               #buttonsWidth=200
                               #buttonTitle='oi',
                               #clickFx=False,
                               #debug=True,
                               find=request.vars.where or 'manufacturer',search=request.vars.what or 'Ferrari',
                               #searchOption=False,
                               #searchButtonLabel='Buscar',
                               #searchButtonTitle='Clique para buscar',
                               #searchFocus=False,
                               #cache=True,
                               #contentType='application/x-www-form-urlencoded; charset=utf-8',
                               #type='get',
                               #dataType='jsonp',
                               #jsonp=True,
                               #jsonpCallback='callback',
                               #findsName=[['name','name']],
                               #hoverFx=False,
                               #loadingOption=True,
                               #loadingText='Carregando...',
                               #messageOption=False,
                               #noResultOption=False,
                               #noResultText='I found nothing ',
                               #page=1,
                               #rows=3,
                               #rowsNumber=[3,25],
                               #params='&blablabla=45',
                               #resize=False,
                               #resultOption=False,
                               #resultText= 'Exibindo {from} - {to} de {total} registros',
                               #scroll=True,height=100,
                               #searchText='Busque aqui',
                               #sortName='name',
                               #sortOrder='asc',
                               #template='template',
                               #templateStyle='blabla',



                                   ),
                  )

    return dict(p=p)

def noadd():
    response.view = 'default/index.html'
    from plugin_PowerGrid.PowerGrid import PowerGrid
    p = PowerGrid(
                  callback=URL('default','callback', extension='json'),
                  buttons=[
                            ('details',URL('plugin_PowerGrid','data',args=['read','products'])+'/${id}','_blank','Details of Record ${id}','modal positive left button','magnifier',[600,500]),
                            ('edit',URL('plugin_PowerGrid','data',args=['update','products'])+'/${id}','_blank','Editing Record ${id}','refreshmodal middle button', 'pen',[600,800]),
                            ('delete',URL('plugin_PowerGrid','data',args=['delete','products'])+'/${id}','_blank','Are you sure you want to delete record ${id}','confirmationmodal right negative button', 'cross'),
                            ('google','http://www.google.com/#hl=en-US&source=hp&q=${name}','_blank','Googling for ${name}','modal right button', 'pin',[900,600]),
                         ],
                  addurl=URL('plugin_PowerGrid','data',args=['create','products']), 
                  addLabel='Add New Record',   
                  addTitle='You are adding a new record',              
                  headers=[['id','Id'], ['name','Name'], ['manufacturer','Manufacturer'],['group_id','Group ID']],
                  #hidecontrolbuttons=True,
                  #hiderefreshbutton=True,
                  hideaddbutton=True,
                  #_id="banana",
                  #target="melancia",
                  #searchBy='equal',
                  options=dict(colsWidth=[30,200,200,100],
                               #width=700,
                               #buttonBackTitle='Back',
                               #buttonMax=4,
                               #buttonNextTitle='Next',
                               #success="""js[function(){alert('Executed on success');}]js""",
                               #before="""js[function(){alert('Executed before');}]js""",
                               #error="""js[function(){alert('Executed on load error');}]js""",
                               #buttonOption=False,
                               #buttonsWidth=200
                               #buttonTitle='oi',
                               #clickFx=False,
                               #debug=True,
                               #find='name',search='J',
                               #searchOption=False,
                               #searchButtonLabel='Buscar',
                               #searchButtonTitle='Clique para buscar',
                               #searchFocus=False,
                               #cache=True,
                               #contentType='application/x-www-form-urlencoded; charset=utf-8',
                               #type='get',
                               #dataType='jsonp',
                               #jsonp=True,
                               #jsonpCallback='callback',
                               #findsName=[['name','name']],
                               #hoverFx=False,
                               #loadingOption=True,
                               #loadingText='Carregando...',
                               #messageOption=False,
                               #noResultOption=False,
                               #noResultText='I found nothing ',
                               #page=1,
                               #rows=3,
                               #rowsNumber=[3,25],
                               #params='&blablabla=45',
                               #resize=False,
                               #resultOption=False,
                               #resultText= 'Exibindo {from} - {to} de {total} registros',
                               #scroll=True,height=100,
                               #searchText='Busque aqui',
                               #sortName='name',
                               #sortOrder='asc',
                               #template='template',
                               #templateStyle='blabla',



                                   ),
                  )

    return dict(p=p)

def nosearch():
    response.view = 'default/index.html'
    from plugin_PowerGrid.PowerGrid import PowerGrid
    p = PowerGrid(
                  callback=URL('default','callback', extension='json'),
                  buttons=[
                            ('details',URL('plugin_PowerGrid','data',args=['read','products'])+'/${id}','_blank','Details of Record ${id}','modal positive left button','magnifier',[600,500]),
                            ('edit',URL('plugin_PowerGrid','data',args=['update','products'])+'/${id}','_blank','Editing Record ${id}','refreshmodal middle button', 'pen',[600,800]),
                            ('delete',URL('plugin_PowerGrid','data',args=['delete','products'])+'/${id}','_blank','Are you sure you want to delete record ${id}','confirmationmodal right negative button', 'cross'),
                            ('google','http://www.google.com/#hl=en-US&source=hp&q=${name}','_blank','Googling for ${name}','modal right button', 'pin',[900,600]),
                         ],
                  addurl=URL('plugin_PowerGrid','data',args=['create','products']), 
                  addLabel='Add New Record',   
                  addTitle='You are adding a new record',              
                  headers=[['id','Id'], ['name','Name'], ['manufacturer','Manufacturer'],['group_id','Group ID']],
                  #hidecontrolbuttons=True,
                  #hiderefreshbutton=True,
                  #hideaddbutton=True,
                  #_id="banana",
                  #target="melancia",
                  #searchBy='equal',
                  options=dict(colsWidth=[30,200,200,100],
                               #width=700,
                               #buttonBackTitle='Back',
                               #buttonMax=4,
                               #buttonNextTitle='Next',
                               #success="""js[function(){alert('Executed on success');}]js""",
                               #before="""js[function(){alert('Executed before');}]js""",
                               #error="""js[function(){alert('Executed on load error');}]js""",
                               #buttonOption=False,
                               #buttonsWidth=200
                               #buttonTitle='oi',
                               #clickFx=False,
                               #debug=True,
                               #find='name',search='J',
                               searchOption=False,
                               #searchButtonLabel='Buscar',
                               #searchButtonTitle='Clique para buscar',
                               #searchFocus=False,
                               #cache=True,
                               #contentType='application/x-www-form-urlencoded; charset=utf-8',
                               #type='get',
                               #dataType='jsonp',
                               #jsonp=True,
                               #jsonpCallback='callback',
                               #findsName=[['name','name']],
                               #hoverFx=False,
                               #loadingOption=True,
                               #loadingText='Carregando...',
                               #messageOption=False,
                               #noResultOption=False,
                               #noResultText='I found nothing ',
                               #page=1,
                               #rows=3,
                               #rowsNumber=[3,25],
                               #params='&blablabla=45',
                               #resize=False,
                               #resultOption=False,
                               #resultText= 'Exibindo {from} - {to} de {total} registros',
                               #scroll=True,height=100,
                               #searchText='Busque aqui',
                               #sortName='name',
                               #sortOrder='asc',
                               #template='template',
                               #templateStyle='blabla',



                                   ),
                  )

    return dict(p=p)

def gridinpopup():
    response.view = 'default/index.html'
    from plugin_PowerGrid.PowerGrid import PowerGrid
    p = PowerGrid(
                  callback=URL('default','callback', extension='json'),
                  buttons=[
                            ('Open another grid',URL('default','onlydata',args=['layout'],vars=dict(where='id'))+'&what=${id}','_blank','Sub grid of record ${id}','refreshmodal positive pill big button','uparrow'),
                    
                         ],
                  addurl=URL('plugin_PowerGrid','data',args=['create','products']), 
                  addLabel='Add New Record',   
                  addTitle='You are adding a new record',              
                  headers=[['id','Id'], ['name','Name'], ['manufacturer','Manufacturer'],['group_id','Group ID']],
                  #hidecontrolbuttons=True,
                  #hiderefreshbutton=True,
                  #hideaddbutton=True,
                  #_id="banana",
                  #target="melancia",
                  #searchBy='equal',
                  minW=930,
                  minH=300,
                  options=dict(colsWidth=[30,200,200,100],
                               #width=700,
                               #buttonBackTitle='Back',
                               #buttonMax=4,
                               #buttonNextTitle='Next',
                               #success="""js[function(){alert('Executed on success');}]js""",
                               #before="""js[function(){alert('Executed before');}]js""",
                               #error="""js[function(){alert('Executed on load error');}]js""",
                               #buttonOption=False,
                               #buttonsWidth=200
                               #buttonTitle='oi',
                               #clickFx=False,
                               #debug=True,
                               find=request.vars.where or '',search=request.vars.what or '',
                               #searchOption=False,
                               #searchButtonLabel='Buscar',
                               #searchButtonTitle='Clique para buscar',
                               #searchFocus=False,
                               #cache=True,
                               #contentType='application/x-www-form-urlencoded; charset=utf-8',
                               #type='get',
                               #dataType='jsonp',
                               #jsonp=True,
                               #jsonpCallback='callback',
                               #findsName=[['name','name']],
                               #hoverFx=False,
                               #loadingOption=True,
                               #loadingText='Carregando...',
                               #messageOption=False,
                               #noResultOption=False,
                               #noResultText='I found nothing ',
                               #page=1,
                               #rows=3,
                               #rowsNumber=[3,25],
                               #params='&blablabla=45',
                               #resize=False,
                               #resultOption=False,
                               #resultText= 'Exibindo {from} - {to} de {total} registros',
                               #scroll=True,height=100,
                               #searchText='Busque aqui',
                               #sortName='name',
                               #sortOrder='asc',
                               #template='template',
                               #templateStyle='blabla',



                                   ),
                  )

    return dict(p=p)

def toexcel():
    response.view = 'default/index.html'
    from plugin_PowerGrid.PowerGrid import PowerGrid
    p = PowerGrid(
                  callback=URL('default','callback', extension='json'),
                  buttons=[
                            ('export to excel',URL('plugin_PowerGrid','data',args=['read','products'])+'/${id}','_blank','Details of Record ${id}','modal positive big button','book'),
                         ],
                  addurl=URL('plugin_PowerGrid','data',args=['create','products']), 
                  addLabel='Add New Record',   
                  addTitle='You are adding a new record',              
                  headers=[['id','Id'], ['name','Name'], ['manufacturer','Manufacturer'],['group_id','Group ID']],
                  #hidecontrolbuttons=True,
                  #hiderefreshbutton=True,
                  #hideaddbutton=True,
                  #_id="banana",
                  #target="melancia",
                  #searchBy='equal',
                  options=dict(colsWidth=[30,200,200,100],
                               #width=700,
                               #buttonBackTitle='Back',
                               #buttonMax=4,
                               #buttonNextTitle='Next',
                               #success="""js[function(){alert('Executed on success');}]js""",
                               #before="""js[function(){alert('Executed before');}]js""",
                               #error="""js[function(){alert('Executed on load error');}]js""",
                               #buttonOption=False,
                               #buttonsWidth=200
                               #buttonTitle='oi',
                               #clickFx=False,
                               #debug=True,
                               #find='name',search='J',
                               #searchOption=False,
                               #searchButtonLabel='Buscar',
                               #searchButtonTitle='Clique para buscar',
                               #searchFocus=False,
                               #cache=True,
                               #contentType='application/x-www-form-urlencoded; charset=utf-8',
                               #type='get',
                               #dataType='jsonp',
                               #jsonp=True,
                               #jsonpCallback='callback',
                               #findsName=[['name','name']],
                               #hoverFx=False,
                               #loadingOption=True,
                               #loadingText='Carregando...',
                               #messageOption=False,
                               #noResultOption=False,
                               #noResultText='I found nothing ',
                               #page=1,
                               #rows=3,
                               #rowsNumber=[3,25],
                               #params='&blablabla=45',
                               #resize=False,
                               #resultOption=False,
                               #resultText= 'Exibindo {from} - {to} de {total} registros',
                               #scroll=True,height=100,
                               #searchText='Busque aqui',
                               #sortName='name',
                               #sortOrder='asc',
                               #template='template',
                               #templateStyle='blabla',



                                   ),
                  )

    return dict(p=p)

def onlydata():
    response.view = 'default/index.html' if request.args(0) != 'layout' else 'default/index2.html'
    from plugin_PowerGrid.PowerGrid import PowerGrid
    p = PowerGrid(
                  callback=URL('default','callback', extension='json'),
                  buttons=[
                            ('details',URL('plugin_PowerGrid','data',args=['read','products'])+'/${id}','_blank','Details of Record ${id}','modal positive button','magnifier',[600,500]),
                          
                         ],
                  addurl=URL('plugin_PowerGrid','data',args=['create','products']), 
                  addLabel='Add New Record',   
                  addTitle='You are adding a new record',              
                  headers=[['id','Id'], ['name','Name'], ['manufacturer','Manufacturer'],['group_id','Group']],
                  as_html=True,
                  #hidecontrolbuttons=True,
                  #hiderefreshbutton=True,
                  #hideaddbutton=True,
                  #_id="banana",
                  #target="melancia",
                  #searchBy='equal',
                  options=dict(colsWidth=[30,200,200,100],
                               #width=700,
                               #buttonBackTitle='Back',
                               #buttonMax=4,
                               #buttonNextTitle='Next',
                               #success="""js[function(){alert('Executed on success');}]js""",
                               #before="""js[function(){alert('Executed before');}]js""",
                               #error="""js[function(){alert('Executed on load error');}]js""",
                               #buttonOption=False,
                               #buttonsWidth=200
                               #buttonTitle='oi',
                               #clickFx=False,
                               #debug=True,
                               find=request.vars.where or '',search=request.vars.what or '',
                               #searchOption=False,
                               #searchButtonLabel='Buscar',
                               #searchButtonTitle='Clique para buscar',
                               #searchFocus=False,
                               #cache=True,
                               #contentType='application/x-www-form-urlencoded; charset=utf-8',
                               #type='get',
                               #dataType='jsonp',
                               #jsonp=True,
                               #jsonpCallback='callback',
                               #findsName=[['name','name']],
                               #hoverFx=False,
                               #loadingOption=True,
                               #loadingText='Carregando...',
                               #messageOption=False,
                               #noResultOption=False,
                               #noResultText='I found nothing ',
                               #page=1,
                               #rows=3,
                               #rowsNumber=[3,25],
                               #params='&blablabla=45',
                               #resize=False,
                               #resultOption=False,
                               #resultText= 'Exibindo {from} - {to} de {total} registros',
                               #scroll=True,height=100,
                               #searchText='Busque aqui',
                               #sortName='name',
                               #sortOrder='asc',
                               #template='template',
                               #templateStyle='blabla',



                                   ),
                  )

    return dict(p=p)

def orders():
    response.view = 'default/index.html' if request.args(0) != 'layout' else 'default/index2.html'
    callback = 'orderscallback' if (not request.vars.get('product',None)) else 'order_by_id'
    from plugin_PowerGrid.PowerGrid import PowerGrid
    p = PowerGrid(
                  callback=URL('default',callback, extension='json') ,
                  buttons=[
                            ('details',URL('plugin_PowerGrid','data',args=['read','orders'])+'/${id}','_blank','Details of Record ${id}','modal positive left pill button','magnifier',[600,250]),
                            ('edit',URL('plugin_PowerGrid','data',args=['update','orders'])+'/${id}','_blank','Editing Record ${id}','refreshmodal right pill button', 'pen',[600,500]),
                          
                         ],
                  addurl=URL('plugin_PowerGrid','data',args=['create','orders']), 
                  addLabel='Add New Record',   
                  addTitle='You are adding a new record',              
                  headers=[['id','Id'], ['customer','Customer'], ['prods','Products'],['date','Date'],['status','status']],
                  as_html=True,
                  #hidecontrolbuttons=True,
                  #hiderefreshbutton=True,
                  #hideaddbutton=True,
                  #_id="banana",
                  #target="melancia",
                  #searchBy='equal',
                  options=dict(colsWidth=[50,150,200,100,100],
                               #width=700,
                               #buttonBackTitle='Back',
                               #buttonMax=4,
                               #buttonNextTitle='Next',
                               #success="""js[function(){alert('Executed on success');}]js""",
                               #before="""js[function(){alert('Executed before');}]js""",
                               #error="""js[function(){alert('Executed on load error');}]js""",
                               #buttonOption=False,
                               #buttonsWidth=200
                               #buttonTitle='oi',
                               #clickFx=False,
                               #debug=True,
                               find=request.vars.where or '',search=request.vars.what or '',
                               #searchOption=False,
                               #searchButtonLabel='Buscar',
                               #searchButtonTitle='Clique para buscar',
                               #searchFocus=False,
                               #cache=True,
                               #contentType='application/x-www-form-urlencoded; charset=utf-8',
                               #type='get',
                               #dataType='jsonp',
                               #jsonp=True,
                               #jsonpCallback='callback',
                               findsName=[['id','id'],['customer','Customer Name'],['products','Products'],['status','status']],
                               #hoverFx=False,
                               #loadingOption=True,
                               #loadingText='Carregando...',
                               #messageOption=False,
                               #noResultOption=False,
                               #noResultText='I found nothing ',
                               #page=1,
                               #rows=3,
                               #rowsNumber=[3,25],
                               #params='&blablabla=45',
                               #resize=False,
                               #resultOption=False,
                               #resultText= 'Exibindo {from} - {to} de {total} registros',
                               #scroll=True,height=100,
                               #searchText='Busque aqui',
                               #sortName='name',
                               #sortOrder='asc',
                               #template='template',
                               #templateStyle='blabla',



                                   ),
                  )

    return dict(p=p)

def order_by_id():
    class Virtual(object):
      def date(self):
        return self.orders.order_date.strftime('%d/%m/%Y')

      def prods(self):
        #print type(self.orders.products)
        return ' / '.join([str(p) for p in self.orders.products])
    from plugin_PowerGrid.CallBack import CallBack
    return CallBack(db.orders.products.contains(request.vars.product), virtualfields=[Virtual()]) 

def orderscallback():
    class Virtual(object):
      def date(self):
        return self.orders.order_date.strftime('%d/%m/%Y')

      def prods(self):
        #print type(self.orders.products)
        return ' / '.join([str(p) for p in self.orders.products])

    from plugin_PowerGrid.CallBack import CallBack
    return CallBack(db.orders.id>0, virtualfields=[Virtual()])   

def htmlinside():
    response.view = 'default/index.html' if request.args(0) != 'layout' else 'default/index2.html'
    from plugin_PowerGrid.PowerGrid import PowerGrid
    p = PowerGrid(
                  callback=URL('default','callback', extension='json'),
                  buttons=[
                            ('details',URL('plugin_PowerGrid','data',args=['read','products'])+'/${id}','_blank','Details of Record ${id}','modal positive button','magnifier',[600,500]),
                          
                         ],
                  addurl=URL('plugin_PowerGrid','data',args=['create','products']), 
                  addLabel='Add New Record',   
                  addTitle='You are adding a new record',              
                  headers=[['id','Id'], ['name','Name'], ['manufacturer','Manufacturer'],['text','Text']],
                  as_html=True,
                  #hidecontrolbuttons=True,
                  #hiderefreshbutton=True,
                  #hideaddbutton=True,
                  #_id="banana",
                  #target="melancia",
                  #searchBy='equal',
                  options=dict(colsWidth=[30,200,200,100],
                               #width=700,
                               #buttonBackTitle='Back',
                               #buttonMax=4,
                               #buttonNextTitle='Next',
                               #success="""js[function(){alert('Executed on success');}]js""",
                               #before="""js[function(){alert('Executed before');}]js""",
                               #error="""js[function(){alert('Executed on load error');}]js""",
                               #buttonOption=False,
                               #buttonsWidth=200
                               #buttonTitle='oi',
                               #clickFx=False,
                               #debug=True,
                               find=request.vars.where or '',search=request.vars.what or '',
                               #searchOption=False,
                               #searchButtonLabel='Buscar',
                               #searchButtonTitle='Clique para buscar',
                               #searchFocus=False,
                               #cache=True,
                               #contentType='application/x-www-form-urlencoded; charset=utf-8',
                               #type='get',
                               #dataType='jsonp',
                               #jsonp=True,
                               #jsonpCallback='callback',
                               #findsName=[['name','name']],
                               #hoverFx=False,
                               #loadingOption=True,
                               #loadingText='Carregando...',
                               #messageOption=False,
                               #noResultOption=False,
                               #noResultText='I found nothing ',
                               #page=1,
                               #rows=3,
                               #rowsNumber=[3,25],
                               #params='&blablabla=45',
                               #resize=False,
                               #resultOption=False,
                               #resultText= 'Exibindo {from} - {to} de {total} registros',
                               #scroll=True,height=100,
                               #searchText='Busque aqui',
                               #sortName='name',
                               #sortOrder='asc',
                               #template='template',
                               #templateStyle='blabla',



                                   ),
                  )

    return dict(p=p)

def withimages():
    response.view = 'default/index.html'
    from plugin_PowerGrid.PowerGrid import PowerGrid
    p = PowerGrid(
                  callback=URL('default','callback_with_virtualfields', extension='json'),
                   buttons=[
                            ('details',URL('plugin_PowerGrid','data',args=['read','products'])+'/${id}','_blank','Details of Record ${id}','modal positive button','magnifier',[600,500]),
                         ],
                  addurl=URL('plugin_PowerGrid','data',args=['create','products']), 
                  addLabel='Add New Record',
                  addTitle='You are adding a new record',                   
                  headers=[['id','id'], ['name','name'], ['manufacturer','manufacturer'],['category','category'],['image','image']],
                  #as_html=False,
                  options=dict(colsWidth=[30,200,200,150,110]),
                  )

    return dict(p=p)

def callback_with_virtualfields():
    from plugin_PowerGrid.CallBack import CallBack
    class Virtual(object):
        def image(self):
            return str(A(IMG(_width=100,_src=URL('default','download',args=self.products.picture)), 
                         _href=URL('default','download',args=self.products.picture),
                         _class='modal',
                         _title='image of record %s' % self.products.id,
                         _w=900,
                         _h=900
                         )
                      )
        
    return CallBack(db.products.id>0, virtualfields=[Virtual()])

def callback():
    from plugin_PowerGrid.CallBack import CallBack        
    return CallBack(db.products.id>0)

def user():
    """
    exposes:
    http://..../[app]/default/user/login
    http://..../[app]/default/user/logout
    http://..../[app]/default/user/register
    http://..../[app]/default/user/profile
    http://..../[app]/default/user/retrieve_password
    http://..../[app]/default/user/change_password
    use @auth.requires_login()
        @auth.requires_membership('group name')
        @auth.requires_permission('read','table name',record_id)
    to decorate functions that need access control
    """
    return dict(form=auth())


def download():
    """
    allows downloading of uploaded files
    http://..../[app]/default/download/[filename]
    """
    return response.download(request,db)


def call():
    """
    exposes services. for example:
    http://..../[app]/default/call/jsonrpc
    decorate with @services.jsonrpc the functions to expose
    supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv
    """
    return service()


#@auth.requires_signature()
def data():
    """
    http://..../[app]/default/data/tables
    http://..../[app]/default/data/create/[table]
    http://..../[app]/default/data/read/[table]/[id]
    http://..../[app]/default/data/update/[table]/[id]
    http://..../[app]/default/data/delete/[table]/[id[
    http://..../[app]/default/data/select/[table]
    http://..../[app]/default/data/search/[table]
    but URLs bust be signed, i.e. linked with
      A('table',_href=URL('data/tables',user_signature=True))
    or with the signed load operator
      LOAD('default','data',args='tables',ajax=True,user_signature=True)
    """
    if request.args(0) == 'deleted':
        return dict(message='Deleted')

    crud.settings.controller = 'default'
    crud.settings.download_url = URL('download')
    def updater(form):
        if form.errors:
            form.append(SCRIPT('alert("Erro");'))
        else:
            form.append(SCRIPT('parent.$.nmTop().close();'))

    crud.settings.update_onaccept = lambda form: updater(form)
    crud.settings.create_onaccept = lambda form: updater(form)
    crud.settings.delete_next = URL('data',args='deleted')

    return dict(form=crud())

def docs():
    response.view = 'default/index.html'
    return dict(p='Documentation is in progress of writing, take a look at examples menu and Index page')

def support():
    from plugin_PowerGrid.PowerGrid import PowerScript
    response.view = 'default/index.html'
    response.files.append(URL('static','plugin_PowerGrid',args=['buttons','stylesheets','css3buttons.css']))
    response.files.append(URL('static','plugin_PowerGrid',args=['modal','styles','nyroModal.css']))
    response.files.append(URL('static','plugin_PowerGrid',args=['modal','js','jquery.nyroModal.custom.min.js']))
    return dict(p=DIV(
                      H1('Doubts, Support, Implementation, Online Training - bruno@blouweb.com'),
                  A(SPAN(_class='icon comment'),'Forum',_title='Blouweb Labs Forum',_class='button big ',_href='https://www.facebook.com/board.php?uid=180466245330580',_target='_blank'),
                  HR(),
                  DIV(_id="disqus_thread"),

                  PowerScript("""
                        

    /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
    
    var disqus_shortname = 'blouweblabs'; // required: replace example with your forum shortname

    // The following are highly recommended additional parameters. Remove the slashes in front to use.
    var disqus_identifier = 'blouweb_powergrid_%s';
    var disqus_url = 'http://labs.blouweb.com/PowerGrid/default/support';

    /* * * DON'T EDIT BELOW THIS LINE * * */
    (function() {
        var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
        dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    })();

                        """ % request.fucntion)

                       ))

def comments():
    response.view = 'default/index.html'
    return dict(p='Leave a general message!')


def donate():
    response.view = 'default/index.html'
    return dict(p=XML(H1('Donate on Paypal to ',SPAN('bruno@blouweb.com',_style='color:blue;'))))

def get():
    response.view = 'default/index.html'
    return dict(p=A('Download at bitbucket',_href='https://bitbucket.org/rochacbruno/powergrid/downloads',_target='_blank'))
            
            

def about():
    info = """  <h2>This plugin is poweredby:</h2>
    <ul>
       <li><a target="_blank" href='http://www.web2py.com'>web2py framework</a> </li>
       <li><a target="_blank" href='http://cursodepython.com.br'>Python</a></li>
       <li><a target="_blank" href='http://www.wbotelhos.com/gridy/'>wbotelhos Jquery Gridy</a></li>
       <li><a target="_blank" href='http://nyromodal.nyrodev.com/'>Jquery nyroModal</a></li>
       <li><a target="_blank" href='http://css3buttons.michaelhenriksen.dk/'>CSS3 Buttons</a></li>
       <li><a target="_blank" href='http://labs.blouweb.com'>Blouweb Power Tools</a></li>
       <li>*<a target="_blank" href='http://www.python-excel.org/'>python-excel xlwt & xlrd</a></li>
       <li>*<a target="_blank" href='http://wijmo.com/widgets/wijmo-open/'>Wijmo Open</a></li> 
    </ul>
    <b>* future implementations under development</b>"""
    return dict(info=XML(info))
